package com.david.musicapp.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.RemoteViews;

import com.david.core.utils.PreferenceUtils;
import com.david.musicapp.PlayService;
import com.david.musicapp.R;
import com.david.musicapp.activity.SongActivity;
import com.david.musicapp.bean.Song;
import com.david.core.utils.ImageUtils;
import com.david.musicapp.utils.SongHelper;
import com.david.musicapp.utils.SongUtils;

public class SongWidget extends AppWidgetProvider {

    public static final String REFRESH_WIDGET = "com.oitsme.REFRESH_WIDGET";
    public static final String PANEL_VIEW_CLICK = "com.oitsme.PANEL_VIEW_CLICK";
    public static final String COLLECTION_VIEW_ACTION = "com.oitsme.COLLECTION_VIEW_ACTION";
    public static final String COLLECTION_VIEW_EXTRA = "com.oitsme.COLLECTION_VIEW_EXTRA";

    /**
     * 桌面小部件更新回调方法，设置view的UI及事件；通过playService的updateWidget触发系统开始更新桌面部件
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {

        for (int appWidgetId : appWidgetIds) {
            RemoteViews remoteViews = getWidgetView(context, 0, true);

            if (remoteViews == null) {
                return;
            }
//            // 调用集合管理器对集合进行更新
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }


    //    static RemoteViews remoteViews;
    public static RemoteViews getWidgetView(Context context, int timeProgress, boolean updateOtherViews) {
        // 获取AppWidget对应的视图
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.song_home_widget);

        Song song = SongHelper.Companion.getInstance().getSongFromId(SongHelper.Companion.getInstance().getCurrentId());

        if (song == null) {
            if (SongHelper.Companion.getInstance().getCurrentList() == null || SongHelper.Companion.getInstance().getCurrentList().size() == 0) {
                return null;
            }
            long songId = PreferenceUtils.Companion.getInstance().getLong("lastSongId");
            song = SongHelper.Companion.getInstance().getSongFromId(songId);

            if (song == null) {
                return null;
            }
        }

        remoteViews.setProgressBar(R.id.music_widget_progress, song.duration / 1000, timeProgress, false);


        if (updateOtherViews) {
            remoteViews.setTextViewText(R.id.music_widget_name, song.name);

            Bitmap bitmap = SongHelper.Companion.getInstance().loadingCover(song.path);
            if (bitmap != null) {
                remoteViews.setImageViewBitmap(R.id.music_widget_img, ImageUtils.toRoundCorner(bitmap, 200));
            } else {
                remoteViews.setImageViewResource(R.id.music_widget_img, R.mipmap.ic_left_round_logo);
            }


            Intent openAppIntent = new Intent(context, SongActivity.class);
            openAppIntent.setAction(PANEL_VIEW_CLICK);
            openAppIntent.putExtra(PlayService.SONG_ACTION_TYPE_KEY, PlayService.isPlaying ? PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_PAUSE : PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_CONTINUE);
            //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
            PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 82, openAppIntent, PendingIntent.FLAG_IMMUTABLE);

            remoteViews.setOnClickPendingIntent(R.id.music_widget_img, openAppPendingIntent);


            remoteViews.setImageViewResource(R.id.music_widget_pause, PlayService.isPlaying ? R.mipmap.player_ic_pause_blue : R.mipmap.player_ic_play_blue);

            remoteViews.setImageViewResource(R.id.music_widget_loop_type, SongUtils.getLoopImg(PlayService.loopType));


            /**8.0后用getForegroundService才能在app被kill后直接启动service*/
            Intent previousIntentBig = new Intent(context, PlayService.class);
            previousIntentBig.setAction(PANEL_VIEW_CLICK);
            previousIntentBig.putExtra(PlayService.SONG_ACTION_TYPE_KEY, PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_PREVIOUS);
            //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
            //requestCode标识pendingintent，设置多个时注意设置不同，否则多个view会执行同一个pendingintent
            //requestCode标识pendingintent，设置多个时注意设置不同，否则多个view会执行同一个pendingintent
            PendingIntent previousPendingIntentBig = PendingIntent.getForegroundService(context, 100,//requestCode标识pendingintent，设置多个时注意设置不同，否则多个view会执行同一个pendingintent
                    previousIntentBig,
                    PendingIntent.FLAG_IMMUTABLE);

            remoteViews.setOnClickPendingIntent(R.id.music_widget_previous, previousPendingIntentBig);


            Intent pauseIntentBig = new Intent(context, PlayService.class);
            pauseIntentBig.setAction(PANEL_VIEW_CLICK);
            pauseIntentBig.putExtra(PlayService.SONG_ACTION_TYPE_KEY, PlayService.isPlaying ? PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_PAUSE : PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_CONTINUE);
            //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
            PendingIntent pausePendingIntentBig = PendingIntent.getForegroundService(context, 101, pauseIntentBig,
                    (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE : 0) | PendingIntent.FLAG_UPDATE_CURRENT);

            remoteViews.setOnClickPendingIntent(R.id.music_widget_pause, pausePendingIntentBig);


            Intent nextIntentBig = new Intent(context, PlayService.class);
            pauseIntentBig.setAction(PANEL_VIEW_CLICK);
            nextIntentBig.putExtra(PlayService.SONG_ACTION_TYPE_KEY, PlayService.SONG_ACTION_TYPE_BIG_NOTIFY_NEXT);
            //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
            PendingIntent nextPendingIntentBig = PendingIntent.getForegroundService(context, 102, nextIntentBig, PendingIntent.FLAG_IMMUTABLE);

            remoteViews.setOnClickPendingIntent(R.id.music_widget_next, nextPendingIntentBig);

            Intent loopIntent = new Intent(context, PlayService.class);
            pauseIntentBig.setAction(PANEL_VIEW_CLICK);
            loopIntent.putExtra(PlayService.SONG_ACTION_TYPE_KEY, SongUtils.getNextLoopType(PlayService.loopType));
//            Log.e("music", "loopType: " + SongUtils.getNextLoopType(PlayService.loopType));
            //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
            PendingIntent loopPendingIntent = PendingIntent.getForegroundService(context, 103, loopIntent, (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE : 0) | PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.music_widget_loop_type, loopPendingIntent);
        }
        return remoteViews;

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.e("music", "refresh widget");
    }
}
